﻿using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;
using System.Security.Cryptography;
using System.Collections.Specialized;
using System.IO;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Net;


public partial class Alipay_Return :NoTheme
{
    /// <summary>
    /// created by sunzhizhi 2006.5.21,sunzhizhi@msn.com。
    /// </summary>
    /// 
    #region Help
    public static string GetMD5(string s, string _input_charset)
    {

        /// <summary>
        /// 与ASP兼容的MD5加密算法
        /// </summary>
       
        MD5 md5 = new MD5CryptoServiceProvider();
        byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
        StringBuilder sb = new StringBuilder(32);
        for (int i = 0; i < t.Length; i++)
        {
            sb.Append(t[i].ToString("x").PadLeft(2, '0'));
        }
        return sb.ToString();
    }

    public static string[] BubbleSort(string[] r)
    {
        /// <summary>
        /// 冒泡排序法
        /// </summary>

        int i, j; //交换标志 
        string temp;

        bool exchange;

        for (i = 0; i < r.Length; i++) //最多做R.Length-1趟排序 
        {
            exchange = false; //本趟排序开始前，交换标志应为假

            for (j = r.Length - 2; j >= i; j--)
            {
                if (System.String.CompareOrdinal(r[j + 1], r[j]) < 0)　//交换条件
                {
                    temp = r[j + 1];
                    r[j + 1] = r[j];
                    r[j] = temp;

                    exchange = true; //发生了交换，故将交换标志置为真 
                }
            }

            if (!exchange) //本趟排序未发生交换，提前终止算法 
            {
                break;
            }

        }
        return r;
    }
    //获取远程服务器ATN结果
    public String Get_Http(String a_strUrl, int timeout)
    {
        string strResult;
        try
        {

            HttpWebRequest myReq = (HttpWebRequest)HttpWebRequest.Create(a_strUrl);
            myReq.Timeout = timeout;
            HttpWebResponse HttpWResp = (HttpWebResponse)myReq.GetResponse();
            Stream myStream = HttpWResp.GetResponseStream();
            StreamReader sr = new StreamReader(myStream, Encoding.Default);
            StringBuilder strBuilder = new StringBuilder();
            while (-1 != sr.Peek())
            {
                strBuilder.Append(sr.ReadLine());
            }

            strResult = strBuilder.ToString();
        }
        catch (Exception exp)
        {

            strResult = "错误：" + exp.Message;
        }

        return strResult;
    }

    #endregion

    protected void Page_Load(object sender, EventArgs e)
    {
   //***************************************************************     
        string alipayNotifyURL = "https://www.alipay.com/cooperate/gateway.do?";
        string key = "pl0426ygo5ah1gpvfmlhc0kh2xk20110"; //partner 的对应交易安全校验码（必须填写）
        string _input_charset = "utf-8";
        string partner = "2088302319713223"; 		     //partner合作伙伴id（必须填写）

        alipayNotifyURL = alipayNotifyURL + "service=notify_verify" + "&partner=" + partner + "&notify_id=" + Request.QueryString["notify_id"];

        //获取支付宝ATN返回结果，true是正确的订单信息，false 是无效的
        string responseTxt = Get_Http(alipayNotifyURL, 120000);
        int i;
        NameValueCollection coll;
        //Load Form variables into NameValueCollection variable.
        coll = Request.QueryString;

        // Get names of all forms into a string array.
        String[] requestarr = coll.AllKeys;

        //进行排序；
        string[] Sortedstr = BubbleSort(requestarr);

       /* for (i = 0; i < Sortedstr.Length; i++)
       { 
          Response.Write("Form: " + Sortedstr[i] + "=" + Request.QueryString[Sortedstr[i]] + "<br>");
       }*/

        //构造待md5摘要字符串 ；

        StringBuilder prestr = new StringBuilder();

        for (i = 0; i < Sortedstr.Length; i++)
        {
            if (Request.Form[Sortedstr[i]] != "" && Sortedstr[i] != "sign" && Sortedstr[i] != "sign_type")
            {
                if (i == Sortedstr.Length - 1)
                {
                    prestr.Append(Sortedstr[i] + "=" + Request.QueryString[Sortedstr[i]]);
                }
                else
                {
                    prestr.Append(Sortedstr[i] + "=" + Request.QueryString[Sortedstr[i]] + "&");

                }
            }
        }
        prestr.Append(key);
//**********************************************************************
        //生成Md5摘要；
       // string mysign = GetMD5(prestr.ToString(), _input_charset);
        string mysign = GetMD5(prestr.ToString(), _input_charset);
        string sign = Request.QueryString["sign"];
        string trade_status = Request.QueryString["trade_status"];
        string orderNum = Request.QueryString["out_trade_no"];
       // Response.Write(prestr.ToString());  //打印返回通知消息，接收到的
        if (mysign == sign && responseTxt == "true" && trade_status == "TRADE_FINISHED")   //验证支付发过来的消息，签名是否正确
        {
               string PayMoney = Request.QueryString["total_fee"].ToString();
               StringBuilder meg = new StringBuilder("\r\n收到支付结果:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + ";订单号:" + Request.QueryString["out_trade_no"] + ";成功收到支付宝返回结果" );
                Pan.Log.WriteLog(meg.ToString(), "AliPayReturn");
                try
                {
                    string buyerEmail = Request.QueryString["buyer_email"];
                    string tradeNo = Request.QueryString["trade_no"];
                    DateTime paydate = DateTime.Now; //DateTime.Parse(Request.Form["notify_time"]);
                    Pan.Log.WriteLog(string.Format("ordernum:{0},buyerEmail:{1},tradeNo:{2},paydate:{3}", orderNum, buyerEmail, tradeNo, paydate));
                    int flag = (new Tuan.BLL.OrderInfo()).Update(orderNum,"1", "7", buyerEmail, tradeNo, paydate);
                    if (flag > 0)
                        Pan.Log.WriteLog(string.Format("数据库操作;订单号:{0},时间:{1} 数据库写入成功", Request.QueryString["out_trade_no"], DateTime.Now.ToString()), "AliPayReturn");
                    else
                        Pan.Log.WriteLog(string.Format("数据库操作;订单号:{0},失败时间:{1},通知重发，已作数据库处理，返回行数:{2}", Request.QueryString["out_trade_no"], DateTime.Now.ToString(), flag), "AliPayReturn");
                }
                catch (Exception dataEx)
                {
                    StringBuilder sbMeg = new StringBuilder("数据库操作出错了：" + DateTime.Now.ToString());
                    sbMeg.Append("; 订单号：");
                    sbMeg.Append(orderNum);
                    sbMeg.AppendLine(";数据库写入失败。");
                    sbMeg.AppendLine("错误消息：" + dataEx.Message);
                    sbMeg.AppendLine("错误方法：" + dataEx.TargetSite.ToString());
                    sbMeg.AppendLine("错误跟踪：" + dataEx.StackTrace);
                    Pan.Log.WriteLog(sbMeg.ToString(), "AliPayReturn");
                    Response.Write("fail");
                    return;
                }
                Response.Write("success");     //返回给支付宝消息，成功

                //Response.Write("success"); 
                //=== 支付成功
                //Response.Redirect("PayInsertDB.aspx?payInterface=支付宝&id=" + Order_Id[0] + "&money=" + PayMoney + "&notifyid=" + Request.QueryString["notify_id"] + "&buyerId=" + Request.QueryString["buyer_id"] + "&sellerId=" + Request.QueryString["seller_id"] + "&login=" + Order_Id[1]);
                Response.Redirect("../SucceedPay.aspx?payInterface=支付宝&money=" + PayMoney + "&NetPayMent=true&DB=true");
                
            }
            else
            {
                //=== 支付失败
                Response.Write("fail");
                Response.Redirect("../SucceedPay.aspx?payInterface=支付宝&money=0&NetPayMent=false&DB=false&orderid=" +  Request.QueryString["out_trade_no"] + "");
           
        }
         
    }
}
